package pcgen.android;

import org.apache.commons.lang.Validate;

import android.content.Context;

public class ResourceUtils
{
	public static int getIdentifier(Context context, String name, String defType, String defPackage)
		throws Throwable
	{
		Validate.notNull(context);
		Validate.notEmpty(name);
		Validate.notEmpty(defType);
		Validate.notEmpty(defPackage);
		
		try
		{
			return context.getResources().getIdentifier(name, defType, defPackage);
		}
		catch(Throwable tr)
		{
			Logger.e(TAG, "getIdentifier", tr);
			throw tr;
		}
	}
	
	public static int getLayoutIdentifier(Context context, String name, String defPackage)
		throws Throwable
	{
		Validate.notNull(context);
		Validate.notEmpty(name);
		Validate.notEmpty(defPackage);
		
		try
		{
			return getIdentifier(context, name, "layout", defPackage);
		}
		catch(Throwable tr)
		{
			Logger.e(TAG, "getLayoutIdentifier", tr);
			throw tr;
		}
	}
	
	public static String getString(Context context, int id)
		throws Throwable
	{
		Validate.notNull(context);
		
		try
		{
			return context.getResources().getString(id);
		}
		catch(Throwable tr)
		{
			Logger.e(TAG, "getString", tr);
			throw tr;
		}
	}
	
	public static String getString(Context context, String name, String defPackage)
		throws Throwable
	{
		Validate.notNull(context);
		Validate.notEmpty(name);
		Validate.notEmpty(defPackage);
		
		try
		{
			return context.getResources().getString(context.getResources().getIdentifier(name, "string", defPackage));
		}
		catch(Throwable tr)
		{
			Logger.e(TAG, "getString", tr);
			throw tr;
		}
	}
	
	public static String getStringRaw(Context context, int id)
		throws Throwable
	{
		Validate.notNull(context);
		
		try
		{
			java.io.InputStream stream = context.getResources().openRawResource(id);

    		byte[] bytes = new byte[1000]; 
    		int numRead = 0; 
    		StringBuilder value = new StringBuilder(); 
    		while ((numRead = stream.read(bytes)) >= 0) 
    			value.append(new String(bytes, 0, numRead));
    		
    		return value.toString();
		}
		catch(Throwable tr)
		{
			Logger.e(TAG, "getStringRaw", tr);
			throw tr;
		}
	}
    
	private static final String TAG = ResourceUtils.class.getSimpleName();
}
